﻿
using System.Diagnostics;
using System.Windows;
using Prism.Events;
using SoonCode.Core;
using SoonCode.FocusTest.Events;
using SoonCode.FocusTest.Models;
using SoonCode.FocusTest.Utils;
using Application = System.Windows.Application;
using MessageBox = HandyControl.Controls.MessageBox;
using SoonCode.FocusTest.ViewModels;
using System.IO;
using System.Windows.Controls;
using HandyControl.Controls;
using SoonCode.FocusTest.Api;

namespace SoonCode.FocusTest.Views
{
    /// <summary>
    /// Main.xaml 的交互逻辑
    /// </summary>
    public partial class Main : BaseWindow
    {
        private IEventAggregator _eventAggregator;
        private StudentWindow student;
        private bool canUpdateApp = false;
        private TestWindow testWindow;
        private WebBrowser browser;
        public Main(IEventAggregator aggregator)
        {
            this._eventAggregator = aggregator;
            InitializeComponent();
            if (ScreenManager.GetScreenCount() < 2)
            {
                MessageBox.Show("您的显示器参数不正确，请正确设置显示器参数后再试。或设备不符合系统要求，请联系供应商提供合格设备！，", "系统提示", MessageBoxButton.OK, MessageBoxImage.Error);
                Application.Current.Shutdown();
            }
            student = new StudentWindow(aggregator);
            ScreenManager.Instance.Show(null, student, 1);

            Login login = new Login(aggregator);

            if (ScreenManager.Instance.ShowDialog(null, login) != true)
            {
                Application.Current.Shutdown();
                return;
            }
            aggregator.GetEvent<WebviewCommandEvent>().Subscribe(OpenBrowser);
            aggregator.GetEvent<OpenTestEvent>().Subscribe(OnOpenTest);
            aggregator.GetEvent<AppUpgradeEvent>().Subscribe(OnUpgrade);
            this.Loaded += Main_Loaded;
            this.Activated += Main_Activated;
            Task.Run(CheckUpdate);
        }

        private void Main_Activated(object? sender, EventArgs e)
        {
            if (canUpdateApp)
            {
                OnUpgrade(null);
            }
        }

        private void OnUpgrade(EventInfo info)
        {
            canUpdateApp = true;
            upgradePanel.Visibility = Visibility.Hidden;
            if (this.IsActive)
            {
                var result = MessageBox.Show("应用程序有新的版本，并已经准备好更新，是否现在更新？"
                    , "程序更新", MessageBoxButton.YesNo, MessageBoxImage.Question);
                if (result == MessageBoxResult.Yes)
                {
                    UpdateApp();
                }
                canUpdateApp = false;
            }
        }

        private void UpdateApp()
        {
            string path = @$"{FileHelper.GetCurrentDir()}update\update_app.exe";
            bool updateTemp = FileHelper.Exists(@$"{FileHelper.GetCurrentDir()}update\update_app.exe");
            if (!updateTemp) return;
            Process.Start(path);
            Environment.Exit(0);
        }
        private async void CheckUpdate()
        {
            UpdateUtil util = new UpdateUtil(this._eventAggregator);
            bool update = await util.CheckUpdate();
            FileHelper.DeleteDirectory(FileHelper.GetCurrentDir() + "update");
            if (update)
            {
                Growl.InfoGlobal("有新的版本可以更新，系统正在为您下载更新包，下载过程不会影响您的评测，下载完成后在您返回主界面时会提示您进行更新！");
                this.Dispatcher.Invoke(() => { upgradePanel.Visibility = Visibility.Visible; });
                util.DownloadFile();
            }
        }

        private void Main_Loaded(object sender, RoutedEventArgs e)
        {
            student.Hide();
            ScreenManager.Instance.Show(this, student, 1);
        }

        private void OnOpenTest()
        {
            if (testWindow == null)
                testWindow = new TestWindow(this._eventAggregator);
            ScreenManager.Instance.Show(this, testWindow);
            this._eventAggregator.GetEvent<PrepareTestEvent>().Publish();

        }

        private void OpenBrowser(WebAppModel p)
        {
            if (browser == null)
                browser = new WebBrowser(this._eventAggregator);
            ScreenManager.Instance.Show(this, browser);
            this._eventAggregator.GetEvent<OpenPageEvent>().Publish(p);
        }
        private void BtnClose_OnClick(object sender, RoutedEventArgs e)
        {
            var result = MessageBox.Show(this, "确定要退出系统吗？", "系统提示", MessageBoxButton.YesNo, MessageBoxImage.Question);
            if (result == MessageBoxResult.Yes)
            {
                Application.Current.Shutdown();
            }

        }

        private void MemberButton_OnClick(object sender, RoutedEventArgs e)
        {
            ArchiveWindow window = new ArchiveWindow();
            ScreenManager.Instance.Show(this, window);
        }


        private void AppListBox_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            AppsModel app = (AppsModel)appListBox.SelectedItem;
            if (app == null) return;
            WebAppModel wm = new WebAppModel()
            {
                title = app.title,
                url = $"{API.Host}{app.url}?orgId={GlobalModel.Instance.OrgInfo.id}&token={GlobalModel.Token}"
            };
            this._eventAggregator.GetEvent<WebviewCommandEvent>().Publish(wm);
            appListBox.SelectedIndex = -1;
        }
    }
}
